package src.main.java.org.collection.exception;

import java.util.ArrayList;
import java.util.Iterator;

public class Test1 {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("王麻子");
        list.add("小李子");
        list.add("李爱华");
        list.add("张金丹");
        list.add("小李");
        list.add("李玉刚");
        System.out.println(list);

        //需求：找出集合中带“李”并删除,下面代码报错
/*        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            if(next.contains("李")){
                list.remove(next);
            }
        }*/

  /*      for (int i = 0; i < list.size(); i++) {//删除时，会导致后面的元素移动，导致索引异常
            String name = list.get(i);
            if(name.contains("李")){
                list.remove(name);
            }
        }*/

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            if(next.contains("李")){
                iterator.remove();//删除迭代器当前遍历的数据，每删除一个数据后，相当于也在底层做了i--
            }
        }
        System.out.println(list);

    }
}
